package com.winspread.ui.edittext

import android.content.Context
import android.text.*
import android.text.method.PasswordTransformationMethod
import android.util.AttributeSet
import android.util.TypedValue
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import androidx.lifecycle.MutableLiveData
import com.winspread.ui.R
import kotlinx.coroutines.*

/**
 *Author: Amin
 *Data: 2021/10/19 10:53
 *
 *Description: 删除，搜索的组合控件
 *
 */
class AutoClearEditText constructor(context: Context?, attrs: AttributeSet? = null) :
    LinearLayout(context, attrs) {


    companion object {
        var mSearchCallback: ((String) -> Unit)? = null

        @JvmStatic
        @BindingAdapter("auto_edit_text")
        fun AutoClearEditText.setEditText(text: MutableLiveData<String>?) {
            CoroutineScope(Dispatchers.Main).launch {
                val selectionStart = editTv.selectionStart
                editTv.setText(text?.value)
                if (selectionStart <= editTv.text.length) {
                    editTv.setSelection(selectionStart)
                }
            }
        }

        @JvmStatic
        @BindingAdapter("auto_edit_text")
        fun AutoClearEditText.setEditTextStr(text: String?) {
            CoroutineScope(Dispatchers.Main).launch {
                val selectionStart = editTv.selectionStart
                editTv.setText(text)
                if (selectionStart <= editTv.text.length) {
                    editTv.setSelection(selectionStart)
                }
            }


        }

        @JvmStatic
        @InverseBindingAdapter(attribute = "auto_edit_text", event = "editTextAttrChanged")
        fun AutoClearEditText.getEdittext(): String {
            return editTv.text.toString()
        }

        @JvmStatic
        @BindingAdapter("editTextAttrChanged", requireAll = false)
        fun AutoClearEditText.editTextAttrChanged(inverseBindingListener: InverseBindingListener?) {
            editTv.addTextChangedListener(object : TextWatcher {
                var temp: String? = null

                override fun afterTextChanged(s: Editable?) {

                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int,
                ) {
                    temp = if (TextUtils.isEmpty(s)) {
                        ""
                    } else
                        s.toString()
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    if (temp!! != s.toString()) {
                        inverseBindingListener?.onChange()
                    }
                    temp = if (TextUtils.isEmpty(s)) {
                        ""
                    } else {
                        s.toString()
                    }
                }
            })

        }

    }

    val view: View = LayoutInflater.from(context).inflate(R.layout.auto_clear_edittext, this, true)
    var editTv: EditText

    private var edit_cardBackgroundColor: Int? = null
    private var text_left_padding: Float? = null
    private var edit_cardCornerRadiu: Float? = null
    private var search: Int? = null
    private var clean: Int? = null
    private var edit_size: Float? = null
    private var edit_color: Int? = null
    private var hint_text_color: Int? = null
    private var hint_text: String? = null
    private var search_vi: Boolean? = true
    private var clear_vi: Boolean? = true
    private var edit_text: String? = null
    private var auto_edit_input_pwd: Boolean? = null




    init {
        val attributes = context?.obtainStyledAttributes(attrs, R.styleable.AutoClearEditText)
        edit_cardBackgroundColor = attributes?.getColor(
            R.styleable.AutoClearEditText_auto_edit_cardBackgroundColor,
            0xFF151A28.toInt()
        )
        edit_cardCornerRadiu =
            attributes?.getDimension(R.styleable.AutoClearEditText_auto_edit_cardCornerRadius, 12f)
        search =
            attributes?.getResourceId(R.styleable.AutoClearEditText_auto_search, R.mipmap.search)
        clean = attributes?.getResourceId(R.styleable.AutoClearEditText_auto_clear, R.mipmap.clean)
        edit_size = attributes?.getDimension(R.styleable.AutoClearEditText_auto_edit_size, 16f)
        edit_color =
            attributes?.getInt(R.styleable.AutoClearEditText_auto_edit_color, 0xBFFFFFFF.toInt())
        search_vi = attributes?.getBoolean(R.styleable.AutoClearEditText_auto_search_vis, true)
        clear_vi = attributes?.getBoolean(R.styleable.AutoClearEditText_auto_clear_vis, false)
        hint_text = attributes?.getString(R.styleable.AutoClearEditText_auto_hint_text)
        edit_text = attributes?.getString(R.styleable.AutoClearEditText_auto_edit_text)
        hint_text_color =
            attributes?.getColor(R.styleable.AutoClearEditText_auto_hint_text_color, 0x40FFFFFF)
        text_left_padding =
            attributes?.getDimension(R.styleable.AutoClearEditText_auto_hint_text_left_padding, 16f)
        auto_edit_input_pwd =
            attributes?.getBoolean(R.styleable.AutoClearEditText_auto_edit_input_pwd, false)
        attributes?.recycle()

        val cardView = view.findViewById<CardView>(R.id.cardview)
        edit_cardBackgroundColor?.let {
            cardView.setCardBackgroundColor(it)
        }
        edit_cardCornerRadiu?.let {
            cardView.radius = it.toFloat()
        }

        editTv = view.findViewById<EditText>(R.id.edit_text)


        auto_edit_input_pwd?.let {
            if (it) {
                editTv.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
                editTv.transformationMethod = PasswordTransformationMethod()
            } else {
                editTv.inputType = InputType.TYPE_CLASS_TEXT
            }
        }

        edit_text?.let {
            editTv.setText(it)
        }


        text_left_padding?.let {
            editTv.setPadding(it.toInt(), 0, it.toInt(), 0)
        }
        hint_text?.let {
            editTv.hint = it
        }
        hint_text_color?.let {
            editTv.setHintTextColor(it)
        }
        edit_size?.let { editTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, it) }
        edit_color?.let { editTv.setTextColor(it) }

        val clear_image = view.findViewById<ImageView>(R.id.clear)
        clean?.let {
            clear_image.setImageResource(it)
        }

        clear_vi?.let {
            if (it) {
                clear_image.visibility = View.VISIBLE
            } else {
                clear_image.visibility = View.GONE
            }
        }

        clear_image.setOnClickListener { editTv.setText("") }


        editTv.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                s?.length?.let {
                    if (it > 0) {
                        clear_image.visibility = VISIBLE
                    } else {
                        clear_image.visibility = GONE
                    }
                }
            }
        })
        //设置回车为搜索
        editTv.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mSearchCallback?.run {
                    invoke(v?.text.toString().trim())
                }
            }
            false
        }


        val search_image = view.findViewById<ImageView>(R.id.search)
        search?.let {
            search_image.setImageResource(it)
        }

        search_vi?.let {
            if (it) {
                search_image.visibility = View.VISIBLE
            } else {
                search_image.visibility = View.GONE
            }
        }

        search_image.setOnClickListener {
            mSearchCallback?.run {
                invoke(editTv.text.toString().trim())
            }
        }
    }

    /**
     * 设置点击扫描按钮的回调
     * @param callback Function1<String, Unit>?
     */
    fun setSearchCallback(callback: ((String) -> Unit)?) {
        mSearchCallback = callback
    }

    /**
     * 设置edittext控制输入方式
     * @param inputFilter Array<out InputFilter>
     */
    fun setInputFilter(vararg inputFilter: InputFilter) {
        editTv.filters = inputFilter
    }




}


